package cn.spike.rockcc.mq.listener;

import cn.spike.rockcc.domain.CourseOrder;
import cn.spike.rockcc.dto.Order2Pay;
import cn.spike.rockcc.service.ICourseOrderService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author:spike
 * @create:2023-03-20 19:58
 */
@Component
@RocketMQTransactionListener(txProducerGroup="tx-order")
public class CourseOrderMQTxListener implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        if(o == null) return RocketMQLocalTransactionState.ROLLBACK;
        CourseOrder courseOrder = JSON.parseObject(JSON.toJSONString(o), CourseOrder.class);
        try {
            courseOrderService.createCourseOrder(courseOrder);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        Order2Pay order2Pay = JSON.parseObject(JSON.toJSONString(message.getPayload()), Order2Pay.class);
        Wrapper<CourseOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no",order2Pay.getOrderNo());
        CourseOrder courseOrder = courseOrderService.selectOne(wrapper);
        if(courseOrder != null) return RocketMQLocalTransactionState.COMMIT;
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
